import {Context} from 'koa'
import UserService from "../service/user.service";
class UserController {
    // 判断用户是否存在
    async isExistedUser(ctx:any,next) {
        let {phone,username}:{phone:string,username:string} = ctx.request.body
        let res = await UserService.find(phone,username)
        if (!res) return await next()
        ctx.body = {
            code: 500,
            msg: "用户存在请换一个名称或手机号"
        }
    }
    // 添加用户
    async addUser(ctx:any) {
        let {phone,username}:{phone:string,username:string} = ctx.request.body
        let res = await UserService.add(phone,username)
        if (!res) return ctx.body = {code: 500,msg:"添加用户失败"}
        ctx.body = {code: 200,msg: "添加用户成功"}
    }
    async getUserList(ctx:Context) {
        // 查询用户
        let pageSize = ctx.query.pageSize || 10
        let page = ctx.query.page || 1
        let keyword = ctx.query.keyword || ''
        let res = await UserService.findAll(pageSize,page,keyword)
        ctx.body = {
            code: 200,
            msg: "获取数据成功",
            total: res.total,
            data: res.data
        }
    }
   async removeUser(ctx:any) {
        let rid = ctx.query.rid
        let res = await UserService.remove(rid)
       if (!res) return ctx.body = {code: 500,msg: "删除用户失败"}
        ctx.body = {code: 200,msg:"删除用户成功"}
    }
    async updateUser(ctx:any) {
        let data = ctx.request.body
        let rid = data.rid
        let setData = {}
        for (let key in data) {
            if (key !== 'rid') {
                setData[key] = data[key]
            }
        }
        let res = await UserService.update(rid, setData)
        if (!res[0]) return ctx.body = {code: 500, msg: "修改失败"}
        ctx.body = {code: 200, msg: "修改成功"}
    }
    async findUser(ctx:Context) {
    }

    async getAllUserList(ctx:Context) {
        // 获取所有的用户列表信息
        let result = await UserService.getUserAll()
        ctx.body = {
            code: 200,
            msg: "获取所有的用户列表信息成功",
            data: result
        }
    }
}


export default new UserController()